package com.chenpeijian.demo.demos.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.ArrayList;

/**
 * @program: student_code
 * @description:
 * @author: 陈培建
 * @create: 2024-12-18 16:06
 **/
@RestController
@RequestMapping("/api/progress")
public class SseController {
    @GetMapping("/start")
    public ResponseBodyEmitter startTask() {
        // 创建一个 ResponseBodyEmitter 实例
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();

        // 模拟一个耗时任务
        new Thread(() -> {
            try {
                for (int i = 1; i <= 100; i += 10) {
                    // 向客户端发送进度
                    emitter.send("Progress: " + i + "%\n");
                    Thread.sleep(1000); // 模拟任务耗时
                }
                emitter.complete(); // 任务完成，关闭连接
            } catch (Exception e) {
                emitter.completeWithError(e); // 出现异常时通知客户端
            }
        }).start();

        return emitter; // 返回 Emitter
    }

}
